<?php
	error_reporting (E_ALL | E_STRICT);
	
	$FT_UNKNOWN = 0;
	$FT_AUDIO = 1;
	$FT_VIDEO = 2;
	$FT_PHOTO = 4;

	require ("config_w.inc.php");
	require ("getid3/getid3.php");
	require ("mp3.inc.php");
	require ("DataBase.class.php");
	
	$getID3 = new getID3();
	
	$db = new DataBase ();
	
	$db->connect ($DB_HOSTNAME, $DB_USERNAME, $DB_PASSWORD, $DB_DATABASE);
	
	if (!$db->isConnected()) die ("Error: ".$db->error());
	
	$db->usetransactions (true);
	
	/*($db = mysql_connect ($DB_HOSTNAME, $DB_USERNAME, $DB_PASSWORD)) or die ("Error: Cound't connect to database\n");
	mysql_select_db ($DB_DATABASE, $db) or die ("Error: ".mysql_error ($db)."\n");*/
	
	$scan_queue = array ();
	
	//while (true)
	{
	
		// cleanup
		// files
		$db->transaction ();
		$qs = new DBStatement ("SELECT * FROM files");
		$files = $db->executeQuery($qs);
		if ($files!=null)
		while (($f=$files->getNext())!=null)
		{
			$filename = $f["filepath"]."/".$f["filename"];
			$found = false;
			foreach ($LIST_SCAN_LOCATIONS as $root_dir)
			{
				if (strncasecmp ($filename, $root_dir, strlen(root_dir))==0) $found = true;
			}
			
			if (!$found || !file_exists ($filename))
			{
				$qs = new DBStatement ("DELETE FROM files WHERE file_id = ?");
				$qs->setNumber (1, $f["id"]);
				$db->executeUpdate($qs);
				usleep ($YIELD_TIME);
			}
		}
		
		$db->commit ();
	
		$scan_queue = $LIST_SCAN_LOCATIONS;
		while (count ($scan_queue)>0)
		{
			$dir = array_pop ($scan_queue);
			print "Scanning ".$dir." ... ";
			$dirlist = scandir ($dir);
			if ($dirlist!=null)
			foreach ($dirlist as $file)
			{
				$filename = $dir."/".$file;
				if (is_dir ($filename) && !is_link ($filename))
				{
					if ($file!="." && $file!=".." && !in_array ($filename, $LIST_NO_SCAN))
					{
						array_unshift ($scan_queue, $filename);
					}
				}
				else if (is_file ($filename))
				{
				
					$db->transaction ();
					$error = 0;
				
					$readfile = 1;
					
					// file
					$file_id = 0;
					$dbfile = $db->getRow ("files", "CONCAT(file_path,\"/\",file_name)", $filename);
					if ($dbfile!=null)
					{
						$stat = stat ($filename);
						if ($stat["mtime"]==$dbfile["file_modify_time"]) $readfile = 0;
						else
						{
							$qs = new DBStatement ("DELETE FROM songs WHERE song_file = ?");
							$qs->setNumber (1, $dbfile["file_id"]);
							$db->executeUpdate ($qs);
							
							/*$qs = new DBStatement ("DELETE FROM Video WHERE hddFile = ?");
							$qs->setNumber (1, $dbfile["id"]);
							$db->executeUpdate ($qs);*/
						
							$qs = new DBStatement ("DELETE FROM files WHERE file_id = ?");
							$qs->setNumber (1, $dbfile["file_id"]);
							if (!$db->executeUpdate ($qs)) 
							{
								print ("Error (file): ".$db->error()."\n");
								$error = 1;
							}
						}
					}
				
					if ($readfile == 1)
					{
						$info = $getID3->analyze ($filename);
						
						$filetype = $FT_UNKNOWN;
						
						if ($info["fileformat"] == "mp3")
						{
						
							$filetypename = "mp3";
							/*print $filename."\n";
							print_r ($info["tags"]);*/
							
							$filetype = $FT_AUDIO;
							
							$track = 0;
							$title = "";
							$artist = "";
							$album = "";
							$comment = "";
							$genre = "(Unknown)";
							$year = 0;
							
							if (isset ($info["tags"]["id3v1"]))
							{
								$tag = &$info["tags"]["id3v1"];
								if (isset ($tag["title"][0])) $title = trim ($tag["title"][0]);
								if (isset ($tag["artist"][0])) $artist = trim ($tag["artist"][0]);
								if (isset ($tag["album"][0])) $album = trim ($tag["album"][0]);
								if (isset ($tag["year"][0])) $year = trim ($tag["year"][0]);
								if (isset ($tag["comment"][0])) $comment = trim ($tag["comment"][0]);
								if (isset ($tag["track"][0])) $track = $tag["track"][0];
								if (isset ($tag["genre"][0])) $genre = trim ($tag["genre"][0]);
							}
							
							if (isset ($info["tags"]["id3v2"]))
							{
								$tag = &$info["tags"]["id3v2"];
								if (isset ($tag["title"][0])) $title = trim ($tag["title"][0]);
								if (isset ($tag["artist"][0])) $artist = trim ($tag["artist"][0]);
								if (isset ($tag["album"][0])) $album = trim ($tag["album"][0]);
								if (isset ($tag["year"][0])) $year = trim ($tag["year"][0]);
								if (isset ($tag["comment"][0])) $comment = trim ($tag["comment"][0]);
								if (isset ($tag["track"][0])) $track = $tag["track"][0];
								if (isset ($tag["genre"][0])) $genre = trim ($tag["genre"][0]);
							}
							
							$artist = trim (str_replace ("/", " ", $artist)); 
							$title = trim (str_replace ("/", " ", $title)); 
							$album = trim (str_replace ("/", " ", $album)); 
							$genre = trim (str_replace ("/", " ", $genre)); 
							
							if ($artist == "") $artist = "(Other Artists)";
							if ($title == "") $title = "(Unknown)";
							if ($album == "") $album = "(Unknown)";
							
							print " <".$artist." - ".$title."> \n";
							
							/* ======================== */
						}
					}
					
					if ($filetype == $FT_AUDIO)
					{
						/* insert into the database */
							
							// filetype
							$filetype_id = $db->getID ("filetypes", "filetype_name", $filetypename, "filetype_id");
							if ($filetype_id==0)
							{
								$qs = new DBStatement ("INSERT INTO filetypes (filetype_name) VALUES (?)");
								$qs->setString (1, $filetypename);
								if ($db->executeUpdate ($qs)) 
								{
									$filetype_id = $db->getInsertID();
								}
								else 
								{
									print ("Error (filetype): ".$db->error()."\n");
									$error = 1;
								}
							}
							
							// file
							$file_id = 0;
							$stat = stat($filename);
							$qs = new DBStatement ("INSERT INTO files (file_name, file_size, file_path, file_type, file_modify_time) VALUES (?, ?, ?, ?, ?)");
							$qs->setString (1, $file);
							$qs->setNumber (2, filesize($filename));
							$qs->setString (3, $dir);
							$qs->setNumber (4, $filetype_id);
							$qs->setNumber (5, $stat["mtime"]);
							if ($db->executeUpdate ($qs)) 
							{
								$file_id = $db->getInsertID();
							}
							else 
							{
								print ("Error (file): ".$db->error()."\n");
								$error = 1;
							}
							
							
							// album
							$album_id = $db->getID ("albums", "album_name", $album, "album_id");
							if ($album_id==0)
							{
								$qs = new DBStatement ("INSERT INTO albums (album_name) VALUES (?)");
								$qs->setString (1, $album);
								if ($db->executeUpdate ($qs)) 
								{
									$album_id = $db->getInsertID();
								}
								else 
								{
									print ("Error (album): ".$db->error()."\n");
									$error = 1;
								}
							}
							
							// artist
							$artist_id = $db->getID ("artists", "artist_name", $artist, "artist_id");
							if ($artist_id==0)
							{
								$qs = new DBStatement ("INSERT INTO artists (artist_name) VALUES (?)");
								$qs->setString (1, $artist);
								if ($db->executeUpdate ($qs)) 
								{
									$artist_id = $db->getInsertID();
								}
								else 
								{
									print ("Error (artist): ".$db->error()."\n");
									$error = 1;
								}
							}
							
							// title
							$title_id = $db->getID ("titles", "title_name", $title, "title_id");
							if ($title_id==0)
							{
								$qs = new DBStatement ("INSERT INTO titles (title_name) VALUES (?)");
								$qs->setString (1, $title);
								if ($db->executeUpdate ($qs)) 
								{
									$title_id = $db->getInsertID();
								}
								else 
								{
									print ("Error (title): ".$db->error()."\n");
									$error = 1;
								}
							}
							
							// genre
							$genre_id = $db->getID ("genres", "genre_name", $genre, "genre_id");
							if ($genre_id==0)
							{
								$qs = new DBStatement ("INSERT INTO genres (genre_name) VALUES (?)");
								$qs->setString (1, $genre);
								if ($db->executeUpdate ($qs)) 
								{
									$genre_id = $db->getInsertID();
								}
								else 
								{
									print ("Error (genre): ".$db->error()."\n");
									$error = 1;
								}
							}
							
							// audio
							$audio_id = 0;
							$qs = new DBStatement ("INSERT INTO songs (song_file, song_title, song_artist, song_album, song_genre, song_year, song_comment, song_length, song_track) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)");
							$qs->setNumber (1, $file_id);
							$qs->setNumber (2, $title_id);
							$qs->setNumber (3, $artist_id);
							$qs->setNumber (4, $album_id);
							$qs->setNumber (5, $genre_id);
							$qs->setNumber (6, $year);
							$qs->setString (7, $comment);
							$qs->setString (8, $info["playtime_seconds"]);
							$qs->setString (9, $track);
							if ($db->executeUpdate ($qs)) 
							{
								$audio_id = $db->getInsertID();
							}
							else 
							{
								print ("Error (audio): ".$db->error()."\n");
								$error = 1;
							}
					}
					
					if ($error == 0) $db->commit ();
					else $db->rollback ();
					usleep ($YIELD_TIME);
				}
			}
			print "done\n";
			usleep ($YIELD_TIME);
		}
		
		// cleanup
		$db->transaction ();
		
		// albums
		$qs = new DBStatement ("DELETE FROM albums WHERE NOT EXISTS (SELECT song_id FROM songs WHERE song_album=album_id)");
		$db->executeUpdate($qs);
		
		// artists
		$qs = new DBStatement ("DELETE FROM artists WHERE NOT EXISTS (SELECT song_id FROM songss WHERE song_artist=artist_id)");
		$db->executeUpdate($qs);
		
		// title
		$qs = new DBStatement ("DELETE FROM titles WHERE NOT EXISTS (SELECT song_id FROM songs WHERE song_title=title_id)");
		$db->executeUpdate($qs);
		
		// genres
		$qs = new DBStatement ("DELETE FROM genres WHERE NOT EXISTS (SELECT song_id FROM songs WHERE song_genre=genre_id)");
		$db->executeUpdate($qs);
		
		$db->commit ();
	}
	
	$db->close();
?>
